﻿// Filters/CustomAuthorizeAttribute.cs
using System.Web.Mvc;

namespace WebApplication1.Filters
{
    public class CustomAuthorizeAttribute : ActionFilterAttribute
    {
        private readonly string _allowedRole;

        public CustomAuthorizeAttribute(string allowedRole = null)
        {
            _allowedRole = allowedRole;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var session = filterContext.HttpContext.Session;

            // 检查用户是否登录
            if (session["UserId"] == null)
            {
                filterContext.Result = new RedirectToRouteResult(
                    new System.Web.Routing.RouteValueDictionary(
                        new { controller = "Account", action = "Login" }));
                return;
            }

            // 如果指定了角色，检查角色权限
            if (!string.IsNullOrEmpty(_allowedRole))
            {
                var userRole = session["Role"]?.ToString();
                if (userRole != _allowedRole)
                {
                    filterContext.Result = new RedirectToRouteResult(
                        new System.Web.Routing.RouteValueDictionary(
                            new { controller = "Account", action = "Login" }));
                    return;
                }
            }

            base.OnActionExecuting(filterContext);
        }
    }
}